package com.gai.shop.dao.impl;

import com.gai.shop.dao.TypeDao;
import com.gai.shop.entity.Type;
import com.gai.shop.util.DataBaseUtil;
import com.gai.shop.util.StrUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.util.ArrayList;
import java.util.List;

public class TypeDaoImpl implements TypeDao {
    private final QueryRunner QR = new QueryRunner();

    /**
     * 查询
     * @return List<Type>
     * @throws Exception
     */
    @Override
    public List<Type> selectTypeAll() throws Exception {
        return QR.query(DataBaseUtil.getConnection(),
                "SELECT * FROM `type`;",
                new BeanListHandler<>(Type.class));
    }

    /**
     * 动态查询
     * @param tname
     * @return
     * @throws Exception
     */
    @Override
    public List<Type> getAllByKey(String tname) throws Exception {
        //写一个固定的sql语句 where 1=1 就是为了方便我们后面的参数的条件拼接
        String sql = "SELECT  * FROM  `type` WHERE 1=1";
        List<Object> param = new ArrayList<>();//用于存放数据的集合，大小不固定
        //判断参数不为空就进行拼接
        if (StrUtils.empty(tname)){
            sql += " AND tname LIKE ?";
            param.add("%" + tname + "%");
        }
        return QR.query(DataBaseUtil.getConnection(),
                sql,
                new BeanListHandler<>(Type.class),
                param.toArray());
    }

    /**
     * 新增商品
     * @param tname
     * @param tinfo
     * @return
     * @throws Exception
     */
    @Override
    public Integer addType(String tname, String tinfo) throws Exception {
        return QR.update(DataBaseUtil.getConnection(),
                "INSERT INTO `type` VALUES (DEFAULT,?,?);",
                tname,
                tinfo);
    }
}
